import pyautogui
import cv2
import numpy as np
import time
import easyocr
import pytesseract
import os
import threading
import tkinter as tk
from queue import Queue, Empty

pyautogui.FAILSAFE = False

# 初始化 EasyOCR
reader = easyocr.Reader(['ch_sim', 'en'])

# Tesseract 安装路径
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'


# 图像预处理
def preprocess_image(image):
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    _, binary_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY_INV)
    denoised_image = cv2.GaussianBlur(binary_image, (3, 3), 0)
    return denoised_image


# 截取指定坐标区域的图像
def capture_region(x, y, width, height):
    region = (x, y, width, height)
    screenshot = pyautogui.screenshot(region=region)
    screenshot = np.array(screenshot)
    screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)
    return screenshot


# 使用 EasyOCR 识别图像中的数字
def recognize_number_easyocr(image, result_queue, stop_event):
    preprocessed_image = preprocess_image(image)
    result = reader.readtext(preprocessed_image, detail=0)
    number = ''.join(filter(str.isdigit, result)) or None
    if number:
        result_queue.put(number)
        stop_event.set()


# 使用 Pytesseract 识别图像中的数字
def recognize_number_tesseract(image, result_queue, stop_event):
    preprocessed_image = preprocess_image(image)
    result = pytesseract.image_to_string(preprocessed_image, config='--psm 6')
    number = ''.join(filter(str.isdigit, result)) or None
    if number:
        result_queue.put(number)
        stop_event.set()


# 启动两个线程来识别数字，并返回第一个有效数字
def recognize_number(image):
    result_queue = Queue()
    stop_event = threading.Event()  # 用于指示线程何时结束

    # 启动 EasyOCR 和 Tesseract 线程
    easyocr_thread = threading.Thread(target=recognize_number_easyocr, args=(image, result_queue, stop_event))
    tesseract_thread = threading.Thread(target=recognize_number_tesseract, args=(image, result_queue, stop_event))

    easyocr_thread.start()
    tesseract_thread.start()

    try:
        # 等待第一个有效的数字结果
        number = result_queue.get(timeout=0.4)
    except Empty:
        number = None

    # 结束线程
    stop_event.set()
    easyocr_thread.join()
    tesseract_thread.join()

    return number


# 大于号绘制
def draw_greater_than():
    os.system("adb -s emulator-5554 shell input touchscreen swipe 500 1250 550 1300 0")
    os.system("adb -s emulator-5554 shell input touchscreen swipe 550 1300 500 1350 0")


# 小于号绘制
def draw_less_than():
    os.system("adb -s emulator-5554 shell input touchscreen swipe 500 1250 450 1300 0")
    os.system("adb -s emulator-5554 shell input touchscreen swipe 450 1300 500 1350 0")


# 等于号绘制
def draw_equal():
    os.system("adb -s emulator-5554 shell input touchscreen swipe 500 1250 600 1250 0")
    os.system("adb -s emulator-5554 shell input touchscreen swipe 500 1300 600 1300 0")


# 比较两个数字大小，并绘制符号
def compare_numbers(num1, num2):
    print(num1, num2)
    if num1 is None or num2 is None:
        return
    num1 = int(num1)
    num2 = int(num2)
    if num1 > num2:
        draw_greater_than()
    elif num1 < num2:
        draw_less_than()
    else:
        draw_equal()


# 全局变量
running = False  # 标志是否在运行
thread = None  # 用来保存线程


# 主逻辑，循环捕捉和比对
def main_logic():
    global running
    coords1 = (200, 590, 240, 150)
    coords2 = (610, 590, 240, 150)

    while running:
        time.sleep(0.37)
        image1 = capture_region(*coords1)
        image2 = capture_region(*coords2)
        number1 = recognize_number(image1)
        number2 = recognize_number(image2)
        compare_numbers(number1, number2)


# 启动线程来运行主逻辑
def start_operation():
    global running, thread
    if not running:
        running = True
        thread = threading.Thread(target=main_logic)
        thread.start()
        print("开始")


# 停止主逻辑
def stop_operation():
    global running
    running = False
    print("停止")


# 创建图形界面
def create_gui():
    root = tk.Tk()
    root.title("自动化控制")
    root.geometry("500x250")

    # 创建开始按钮
    start_button = tk.Button(root, text="开始", command=start_operation, width=10, height=2)
    start_button.pack(pady=10)

    # 创建停止按钮
    stop_button = tk.Button(root, text="停止", command=stop_operation, width=10, height=2)
    stop_button.pack(pady=10)

    root.mainloop()


# 启动图形界面
if __name__ == "__main__":
    create_gui()
